<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="searchForm" :model="searchForm" :inline="true" class="demo-form-inline">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="searchForm.username" clearable placeholder="请输入用户名" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="searchForm.sex" clearable placeholder="请选择性别" class="filter-item" style="width: 130px">
            <el-option v-for="item in sexOptions" :key="item.key" :label="item.label+'('+item.value+')'" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间排序" prop="sort">
          <el-select v-model="searchForm.sort" clearable placeholder="请选择排序" style="width: 140px" class="filter-item" @change="handleFilter">
            <el-option v-for="item in sortOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="resetSearchForm">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-button type="primary" @click="editUserVisible = true">创建用户</el-button>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="index" width="60">
        <template slot-scope="scope">
          {{ getSerialNum(scope.$index, searchForm.curPage, searchForm.pageSize) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="200">
        <template slot-scope="scope">
          {{ scope.row._id }}
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="头像">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.userPhoto && scope.row.userPhoto.path"
            :src="scope.row.userPhoto && scope.row.userPhoto.path"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.sex === 1 ? '男' : scope.row.sex === 2 ? '女' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="140" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="140" align="center">
        <template slot-scope="scope">
          {{ scope.row.modifyTime ? moment(scope.row.modifyTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="100"
      >
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEditVisible(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="searchForm.curPage" :limit.sync="searchForm.pageSize" @pagination="getList" />

    <!--  创建用户  -->
    <el-dialog :title="userForm._id ? '编辑用户' : '创建用户'" :visible.sync="editUserVisible" :before-close="cancelCreate">
      <el-form ref="userForm" :model="userForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生活照" prop="userPhotos">
          <el-upload
            ref="files"
            class="upload-demo"
            action="/api/users/create"
            :auto-upload="false"
            :with-credentials="true"
            list-type="picture"
            name="file"
            :data="userForm"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="handleFilesChange"
            :on-success="handleAvatarSuccess"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 jpg、png、gif 文件，且不超过 200kb </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="userForm.age" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="3">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userForm.password" :disabled="!!userForm._id" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCreate">取 消</el-button>
        <el-button type="primary" @click="submitUserForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import qs from 'querystring'
import moment from 'moment'
import { createUser, deleteUser, editUser, getList } from '@/api/usersManage'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves' // waves directive
import { getToken } from '@/utils/auth'
import { getSerialNum } from '@/utils'

export default {
  name: 'UsersManageList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      headers: {
        // 'X-token': getToken()
      },
      editUserVisible: false, // 创建用户显示
      userForm: {
        username: '',
        age: null,
        sex: null,
        password: ''
      }, // 用户表单
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      list: [], // 列表数据
      listLoading: true, // 表格loading
      total: 0, // 列表总条数
      sexOptions: [
        {
          label: '男',
          value: 1
        }, {
          label: '女',
          value: 2
        }, {
          label: '未知',
          value: 3
        }
      ], // 性别枚举
      sortOptions: [{ label: '正序', value: 1 }, { label: '倒序', value: -1 }],
      searchForm: {
        curPage: 1,
        pageSize: 10,
        username: '',
        sex: null,
        sort: -1
      }, // 列表总条数
      fileList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleFilter() {
      this.searchForm.curPage = 1
      this.getList()
    },

    // 重置查询表单
    resetSearchForm() {
      this.$refs.searchForm.resetFields()
      this.handleFilter()
    },

    getList() {
      this.listLoading = true
      getList(this.searchForm).then(({ data: { dataList, total }}) => {
        this.total = total
        this.list = dataList || []
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },

    // 提交用户表单
    submitUserForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (!this.userForm._id) {
            this.createUser()
          } else {
            this.editUser()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 创建用户
    createUser() {
      if (this.fileList.length) {
        this.$refs.files.submit()
      } else {
        createUser(qs.stringify(this.userForm)).then(({ code }) => {
          if (code === 20000) {
            Message.success('创建成功！')
            this.editUserVisible = false
            this.$refs.userForm.resetFields()
            this.userForm = {}
            this.searchForm.curPage = 1
            this.getList()
          }
        })
      }
    },

    // 取消创建用户
    cancelCreate() {
      this.editUserVisible = false
      this.$refs.userForm.resetFields()
      this.fileList = []
      this.$refs.files.clearFiles()
      this.userForm = {}
    },

    // 删除用户
    del(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser({ id: row._id }).then(({ code }) => {
          if (code === 20000) {
            Message.success('删除成功！')
            if ((this.list.length - 1) === 0) { // 如果当前页数据已删完，则去往上一页
              this.searchForm.curPage -= 1
            }
            this.getList()
          }
        })
      })
    },

    // 处理编辑用户弹窗
    handleEditVisible(row) {
      this.userForm = row
      console.log('row', row)
      if (row.userPhoto) {
        this.fileList = [{
          name: row.userPhoto.filename,
          url: row.userPhoto.path
        }]
      }
      this.editUserVisible = true
    },

    // 编辑用户
    editUser() {
      const params = {
        id: this.userForm._id,
        username: this.userForm.username,
        sex: this.userForm.sex,
        age: this.userForm.age,
        password: this.userForm.password
      }
      editUser(qs.stringify(params)).then(({ code }) => {
        if (code === 20000) {
          Message.success('修改成功！')
          this.editUserVisible = false
          this.$refs.userForm.resetFields()
          this.userForm = {}
          this.getList()
        }
      })
    },

    handleFilesChange(file, fileList) {
      this.fileList = fileList
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 10000) {
        this.$message.error(res.message)
        this.fileList.splice(this.fileList.length, 1)
      } else {
        Message.success('创建成功！')
        this.editUserVisible = false
        this.$refs.userForm.resetFields()
        this.userForm = {}
        this.searchForm.curPage = 1
        this.getList()
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },

    getSerialNum,
    moment
  }
}
</script>
